# -*- coding: utf-8 -*-
#   this is the core plugin of smvn
# install : install to local repo
# deploy  : deploy to svn, 默认xml
# export  : export to a local dir
# checkout: checkout to local repo
# fetch   : from SVN -> local repo -> local dir

from __future__ import unicode_literals, print_function

import logging
import sys
import tempfile

from smvn.config import *
from smvn.util import *
from smvn.artifact import Artifact
from smvn.repo import Repo
from smvn.pom import Pom,XmlPom
from smvn.core import get_all_info, pjoin, get_xml, print_map

dr=Repo()

def help_handler(fmap, args):
    print(
"""
    info    pom.xml                 get info of a pom
    ls        cn/com/crscd          list remote repo list
    lls        cn/com/crscd         local list repo list
    install [-Dvar=value] s.pom.xml install dev tree files to local repo
    pinstall [-Dvar=value] spom.xml install files to local repo [comp. mode]
    deploy  [-Dvar=value] s.pom.xml deploy local repo to remote repo
    pid     [-Dvar=value] s.pom.xml pinstall and deploy
    status  [-Dvar=value] s.pom.xml check status of local repo
    search  [-Dvar=value] s.pom.xml search dependency comp. 
    checkout [-Dvar=value] pom.xml  checkout remote repo comp. to local repo
    rfetch pom.xml                  get files to current dir from remote repo
    fetch pom.xml                   get file to current dir from local repo
    resolve pom.xml                 resolve dependency tree
    resolvep pom.xml                resolve dependency tree in comp. mode \
""")

def info_handler(fmap, args):
    p, r = get_all_info(fmap, get_xml(args))
    print(p)

def lls_handler(fmap, args):
    print(dr.local_list(args[1]))

def ls_handler(fmap, args):
    print(dr.svn_list(args[1]))

def deploy_handler(fmap, args):
    """
    将local repo中的内容发布到svn
    """
    p, r = get_all_info(fmap, get_xml(args))
    a = Artifact(p.groupId, p.artifactId, p.version)
    dpath = a.get_dir()
    dirname, ver = r.search_svn(p.groupId, p.artifactId, p.version)
    if (ver == ""):
        print("Deploying", r.localrepo, "to", dpath)
        print(r.svn_import_dir(r.localrepo+'/'+dpath, dpath, a))
    else:
        r.svn_check(a)
        r.svn_commit(a)

def install_files(l, r, a, prefix):
    for h in l:
        # 将头文件复制，并按照命名规则改名
        logging.info("installing file %s", prefix+'/'+h)
        r.install_file(prefix+'/'+h, a)

def install_mfiles(m, r, a, prefix=""):
    # install files from map
    for h, fl in m.items():
        # 将头文件目录复制
        logging.info("installing hdirs %s", prefix+'/'+h)
        if len(fl) == 0:
            r.install_dir(pjoin(prefix, h), a, h)
        else:
            for item in fl:
                r.install_file(pjoin(prefix, h, item), a, pjoin(h, item))

def status_files(l, r, a, prefix):
    for h in l:
        # 将头文件复制，并按照命名规则改名
        r.check_file(pjoin(prefix, h), a)

def status_mfiles(m, r, a, prefix=""):
    for h, fl in m.items():
        if len(fl) == 0:
            pass
        else:
            for item in fl:
                r.check_file(pjoin(prefix, h, item), a, pjoin(h, item))

def status_handler(fmap, args):
    """
    检查local repo中的文件状态
    """
    #if (args[1][-4:] == '.xml'):
    p, r = get_all_info(fmap, get_xml(args))
    a = Artifact(p.groupId, p.artifactId, p.version)
    logging.info("Checking ...")
    status_files (p.headers      , r, a, p.get_header_prefix())
    status_files (p.libs         , r, a, p.get_lib_prefix()  )
    status_mfiles(p.headerdirs   , r, a, p.get_header_prefix())
    status_mfiles(p.resourcedirs , r, a)
    r.check_file('pom.xml', a)

def search_handler(fmap, args):
    p, r = get_all_info(fmap, get_xml(args))
    print(r.search_svn(p.groupId, p.artifactId, p.version))

def libinstall_handler(fmap, args):
    p, r = get_all_info(fmap, get_xml(args))
    a = Artifact(p.groupId, p.artifactId, p.version, p.compiler)
    if len(args) > 1:
        for l in args[1:]:
            lname = p.get_full_libname(l)
            print(a.get_long_filename(lname))
            r.install_file(pjoin(p.get_lib_prefix(), lname), a)
    else:
        for l in p.libs:
            lname = p.get_full_libname(l)
            print(l, a.get_long_filename(lname))
        #install_files (p.libs         , r, a, p.get_lib_prefix()  )

def pinstall_handler(fmap, args):
    """
    @brief 作为第三方模块的install命令
    """
    p, r = get_all_info(fmap, get_xml(args))
    a = Artifact(p.groupId, p.artifactId, p.version)
    install_files (p.headers      , r, a, p.get_header_prefix())
    install_files (p.libs         , r, a, p.get_lib_prefix()  )
    install_mfiles(p.headerdirs   , r, a, p.get_header_prefix())
    install_mfiles(p.resourcedirs , r, a)

    # 后续可考虑增加可靠性
    if fmap.flag_get('__redefined'):
        p.write_xml(pjoin(r.localrepo, p.get_dir(), 'pom.xml'))
    else:
        r.install_file(args[1], a, "pom.xml")
    #tname = tempfile.NamedTemporaryFile().name
    #p.write_xml(tname)
    #r.install_file(tname, a, "pom.xml")

def install_handler(fmap, args):
    """
    @brief 作为开发模块的install命令
    """
    p, r = get_all_info(fmap, get_xml(args))
    a = Artifact(p.groupId, p.artifactId, p.version)
    install_files (p.headers      , r, a, p.get_headersrc_prefix())
    install_mfiles(p.headerdirs   , r, a, p.get_headersrc_prefix())
    install_files (p.libs         , r, a, p.get_lib_prefix()  )
    install_mfiles(p.resourcedirs , r, a)

    # 后续可考虑增加可靠性
    if fmap.flag_get('__redefined'):
        p.write_xml(pjoin(r.localrepo, p.get_dir(), 'pom.xml'))
    else:
        r.install_file(args[1], a, "pom.xml")

def checkout_handler(fmap, args):
    """
    @brief 将svn上的artiface下载到本地
    """
    p, r = get_all_info(fmap, get_xml(args))
    r.download_artifact(p.groupId, p.artifactId, p.version)

def rfetch_handler(fmap, args):
    """
    从svn取回artifact
    """
    p, r = get_all_info(fmap, get_xml(args))
    dirname , ver = r.search_svn(p.groupId, p.artifactId, p.version)
    #r.fetch(dirname, ver, '.'); sys.exit(-1)
    if ver != "":
        rm = r.svn_resolve(p.groupId, p.artifactId, ver[0:-1])
        #print(rm, ver)
        for k, v in rm.items():
            #print(k, v)
            r.fetch(k, v, '.')
    else:
        # 若主artifact无法下载，可考虑下载dependenci
        if p.dependencies is not None:
            for dp in p.dependencies:
                rm = r.svn_resolve(dp.groupId, dp.artifactId, dp.version)
                for k, v in rm.items():
                    print(k, v)
                    r.fetch(k, v, '.')


def fetch_handler(fmap, args):
    """
    从本地或svn取回artifact, 不获取本身组件
    """
    p, r = get_all_info(fmap, get_xml(args))
    # 输入1，表示不对自己进行转换
    rm = r.local_resolve_pom(p, 1)
    #logging.info("Fetching %s as %s", p, rm)
    for k, v in rm.items():
        logging.debug('=== %s %s'%(k, v))
        r.fetch(k, v, '.')

def pfetch_handler(fmap, args):
    """
    获取单独的模块
    """
    p, r = get_all_info(fmap, get_xml(args))
    r.fetch(p.dirpath, p.version, '.')
    #logging.info("Fetching %s", p)

def resolvep_handler(fmap, args):
    """
    resolved pure handler，即不包含自身
    """
    p, r = get_all_info(fmap, get_xml(args))
    logging.info('resolvedp %s' % p)
    for dp in p.dependencies:
        print("==dependency for %s.%s %s"%(dp.groupId, dp.artifactId, dp.version))
        m = r.local_resolve(dp.groupId, dp.artifactId, dp.version)
        print_map(m, "====")

def resolve_handler(fmap, args):
    """
    resolved ，包含自身
    """
    p, r = get_all_info(fmap, get_xml(args))
    m = r.local_resolve(p.groupId, p.artifactId, p.version)
    print("==dependency for %s.%s %s"%(p.groupId, p.artifactId, p.version))
    print_map(m)

def pid_handler(fmap, args):
    """
    pinstall and deploy modules
    """
    pinstall_handler(fmap, args)
    deploy_handler(fmap, args)

def ver_handler(fmap, args):
    print("version!")
